package com.spring.sunflower.anchor;

import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;

import com.bumptech.glide.Glide;
import com.google.android.flexbox.FlexboxLayout;
import com.google.android.material.chip.Chip;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.makeramen.roundedimageview.RoundedImageView;
import com.spring.sunflower.R;
import com.spring.sunflower.base.BaseActivity;
import com.spring.sunflower.bean.AnchorDetailBean;
import com.spring.sunflower.bean.AnchorGiftReceivedBean;
import com.spring.sunflower.bean.LabelBean;
import com.spring.sunflower.common.ReportActivity;
import com.spring.sunflower.common.VideoPlayActivity;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.conversation.ChatActivity;
import com.spring.sunflower.util.AppUtils;
import com.spring.sunflower.util.DisplayUtils;
import com.spring.sunflower.util.StatusBarUtil;
import com.spring.sunflower.widget.CustomBubbleAttachPopup;
import com.youth.banner.Banner;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Kevin on 2021/6/2<br/>
 * <p>
 * Describe:<br/>
 */
public class AnchorInfoActivity extends BaseActivity<AnchorInfoPresenter> implements AnchorContract.AnchorInfoView, View.OnClickListener {
    private Banner banner;
    private TextView tvName, tvAge, tvAddress, tvID,
            tvEmotionState, tvEducation, tvHeight, tvHouse,
            tvIncome, tvGender, tvSign, tvTitle;
    private List<AnchorDetailBean.DatasBean.PhotoVOListBean> bannerData = new ArrayList<>();
    private AnchorBannerAdapter anchorBannerAdapter;
    private NestedScrollView nestedScrollView;
    private int mOffset = 0;
    private int mScrollY = 0;
    private Toolbar toolbar;
    private FlexboxLayout fblHobby, fblGift, fblVideoShow;
    private LinearLayout llContainer;
    private ImageView ivGiftArrow, ivVideoArrow;
    private ActionBar actionBar;
    private String anchorID;
    private TextView tvFunction;
    private boolean mHasBlacked;
    private boolean mHasFollowed;
    private List<LabelBean.DatasBean> mLabelData = new ArrayList<>();
    private List<String> mLabelNameList = new ArrayList<>();
    private TextView tvAccost;
    private LinearLayout llVideoCall, llMessageChat, llGiftSend;
    private ImageView bannerPlaceHolder;
    private String mAvatarUrl;

    @Override
    public void initView() {
        Intent intent = getIntent();
        anchorID = intent.getStringExtra(Constant.KEY_TARGET_ID);
        String userID = getField(Constant.KEY_USERID, "");
        toolbar = findViewById(R.id.toolBar);
        tvTitle = findViewById(R.id.tv_title);
        tvFunction = findViewById(R.id.tv_function);
        AppUtils.setFont(this, tvFunction);
        tvName = findViewById(R.id.tvName);
        tvAge = findViewById(R.id.tvAge);
        tvAddress = findViewById(R.id.tvAddress);
        tvID = findViewById(R.id.tvID);
        banner = findViewById(R.id.banner);
        nestedScrollView = findViewById(R.id.nestedScrollView);
        llContainer = findViewById(R.id.ll_container);
        tvGender = findViewById(R.id.tvGender);
        tvSign = findViewById(R.id.tvSign);
        tvEmotionState = findViewById(R.id.tvEmotionState);
        tvEducation = findViewById(R.id.tvEducation);
        tvHeight = findViewById(R.id.tvHeight);
        tvHouse = findViewById(R.id.tvHouse);
        tvIncome = findViewById(R.id.tvIncome);
        fblHobby = findViewById(R.id.fblHobby);
        fblGift = findViewById(R.id.fblGift);
        fblVideoShow = findViewById(R.id.fblVideoShow);
        ivGiftArrow = findViewById(R.id.ivGiftArrow);
        ivVideoArrow = findViewById(R.id.ivVideoArrow);

        tvAccost = findViewById(R.id.tvAccost);
        llVideoCall = findViewById(R.id.llVideoCall);
        llMessageChat = findViewById(R.id.llMesssageChat);
        llGiftSend = findViewById(R.id.llGiftSend);
        bannerPlaceHolder = findViewById(R.id.bannerPlaceHolder);

        ViewGroup.LayoutParams layoutParams = banner.getLayoutParams();
        int screenWidth = DisplayUtils.getScreenWidth(this);
        layoutParams.width = screenWidth;
        layoutParams.height = screenWidth;
        banner.setLayoutParams(layoutParams);
        anchorBannerAdapter = new AnchorBannerAdapter(this, bannerData);
        banner.setAdapter(anchorBannerAdapter);
        mPresenter.getAnchorDetail(anchorID);
        mPresenter.getGiftLogReceived(anchorID, "1");
        mPresenter.getHasBlacked(anchorID, userID);
        mPresenter.getHasFollowed(anchorID);
        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            int lastScrollY = 0;
            int h = DisplayUtils.dip2px(AnchorInfoActivity.this, 170);
            int color = ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary) & 0x00ffffff;
            int titleColor = ContextCompat.getColor(getApplicationContext(), R.color.white) & 0x00ffffff;

            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (lastScrollY < h) {
                    scrollY = Math.min(h, scrollY);
                    mScrollY = scrollY > h ? h : scrollY;
//                    buttonBar.setAlpha(1f * mScrollY / h);
                    toolbar.setBackgroundColor(((255 * mScrollY / h) << 24) | color);
//                    ivParallax.setTranslationY(mOffset - mScrollY);
                    tvTitle.setTextColor((255 * mScrollY / h) << 24 | titleColor);
                }
                lastScrollY = scrollY;
            }
        });
        toolbar.setBackgroundColor(0);
        tvTitle.setTextColor(0);
        actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
        StatusBarUtil.immersive(this);
        StatusBarUtil.setPaddingSmart(this, toolbar);
        ivVideoArrow.setOnClickListener(this);
        ivGiftArrow.setOnClickListener(this);
        tvFunction.setOnClickListener(this::onClick);
        tvAccost.setOnClickListener(this::onClick);
        llVideoCall.setOnClickListener(this::onClick);
        llMessageChat.setOnClickListener(this::onClick);
        llGiftSend.setOnClickListener(this::onClick);
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_anchor_info;
    }

    @Override
    public AnchorInfoPresenter setPresenter() {
        return new AnchorInfoPresenter(this);
    }

    @Override
    public void showAnchorData(AnchorDetailBean.DatasBean data) {
        List<AnchorDetailBean.DatasBean.PhotoVOListBean> photoVOList = data.getPhotoVOList();
        anchorBannerAdapter.updateData(photoVOList);
        if (photoVOList.size() > 0) {
            banner.setVisibility(View.VISIBLE);
            bannerPlaceHolder.setVisibility(View.GONE);
        } else {
            banner.setVisibility(View.GONE);
            bannerPlaceHolder.setVisibility(View.VISIBLE);
            mAvatarUrl = data.getPhoto();
            Glide.with(this)
                    .load(mAvatarUrl)
                    .into(bannerPlaceHolder);
        }
        tvAge.setText(data.getAge() + "岁");
        tvName.setText(data.getNickname());
        tvTitle.setText(data.getNickname());
        tvID.setText("ID号：" + data.getId());
        List<AnchorDetailBean.DatasBean.HobbiesListBean> hobbiesList = data.getHobbiesList();
        for (AnchorDetailBean.DatasBean.HobbiesListBean hobby : hobbiesList) {
            Chip chip = generateHobby(hobby.getName());
            fblHobby.addView(chip);
        }
        tvAddress.setText(data.getCity());
        tvHeight.setText(data.getHeight() + "cm");
        List<AnchorDetailBean.DatasBean.HousingVBean> housingV = data.getHousingV();
        tvHouse.setText(housingV.size() > 0 ? housingV.get(0).getName() : "保密");
        List<AnchorDetailBean.DatasBean.MaritalStatusVBean> maritalStatusV = data.getMaritalStatusV();
        tvEmotionState.setText(maritalStatusV.size() > 0 ? maritalStatusV.get(0).getName() : "保密");
        List<AnchorDetailBean.DatasBean.IncomeVBean> incomeV = data.getIncomeV();
        tvIncome.setText(incomeV.size() > 0 ? incomeV.get(0).getName() : "保密");
        List<AnchorDetailBean.DatasBean.EducationVBean> educationV = data.getEducationV();
        tvEducation.setText(educationV.size() > 0 ? educationV.get(0).getName() : "保密");
        String sex = data.getSex();
        if ("1".equals(sex)) {
            tvGender.setText(getString(R.string.font_male));
            tvGender.setTextColor(Color.BLUE);
        } else {
            tvGender.setText(getString(R.string.font_female));
            tvGender.setTextColor(Color.RED);
        }
        AppUtils.setFont(this, tvGender);
        tvSign.setText(data.getSignature());
        List<AnchorDetailBean.DatasBean.VideoDetailVOListBean> videoDetailVOList = data.getVideoDetailVOList();
        if (videoDetailVOList.size() > 0) {
            ivVideoArrow.setVisibility(View.VISIBLE);
            if (videoDetailVOList.size() > 4) {
                for (int i = 0; i < 4; i++) {
                    AnchorDetailBean.DatasBean.VideoDetailVOListBean videoDetailVOListBean = videoDetailVOList.get(i);
                    String videoFirstPhotoUrl = videoDetailVOListBean.getVideoFirstPhotoUrl();
                    String videoPath = videoDetailVOListBean.getVideoPath();
                    View view = generateVideoShow(videoFirstPhotoUrl, videoPath);
                    fblVideoShow.addView(view);
                }
            } else {
                for (AnchorDetailBean.DatasBean.VideoDetailVOListBean d : videoDetailVOList) {
                    String videoFirstPhotoUrl = d.getVideoFirstPhotoUrl();
                    String videoPath = d.getVideoPath();
                    View view = generateVideoShow(videoFirstPhotoUrl, videoPath);
                    fblVideoShow.addView(view);
                }
            }
        } else {
            ivVideoArrow.setVisibility(View.GONE);
        }

    }

    @Override
    public void showGiftReceived(List<AnchorGiftReceivedBean.DatasBean> data) {
        if (data.size() > 0) {
            ivGiftArrow.setVisibility(View.VISIBLE);
            if (data.size() > 4) {
                for (int i = 0; i < 4; i++) {
                    AnchorGiftReceivedBean.DatasBean datasBean = data.get(i);
                    String imagePath = datasBean.getImagePath();
                    String number = datasBean.getNumber();
                    View view = generateGift(imagePath, number);
                    fblGift.addView(view);
                }
            } else {
                for (AnchorGiftReceivedBean.DatasBean d : data) {
                    String imagePath = d.getImagePath();
                    String number = d.getNumber();
                    View view = generateGift(imagePath, number);
                    fblGift.addView(view);
                }
            }
        } else {
            ivGiftArrow.setVisibility(View.GONE);
        }

    }

    @Override
    public void hasFollowed(boolean hasFollowed) {
        mHasFollowed = hasFollowed;
    }

    @Override
    public void setFollowedSuccess() {
        mHasFollowed = !mHasFollowed;
        showToast(mHasFollowed ? "已关注" : "已取消");
    }

    @Override
    public void setFollowedFailed() {

    }

    @Override
    public void hasBlacked(boolean hasBlacked) {
        mHasBlacked = hasBlacked;
    }

    @Override
    public void blackAddSuccess() {
        mHasBlacked = true;
        showToast("已拉黑");
    }

    @Override
    public void blackAddFailed() {
        mHasBlacked = false;
        showToast("拉黑失败");
    }

    @Override
    public void blackRemoveSuccess() {
        mHasBlacked = false;
        showToast("已解除");
    }

    @Override
    public void blackRemoveFailed() {
        mHasBlacked = true;
        showToast("解除失败");
    }

    @Override
    public void showReportType(List<LabelBean.DatasBean> data) {
        mLabelData = data;
        mLabelNameList.clear();
        for (LabelBean.DatasBean d : data) {
            String name = d.getName();
            mLabelNameList.add(name);
        }
        String[] stringArr = mLabelNameList.toArray(new String[mLabelNameList.size()]);
        new XPopup.Builder(this)
                .hasShadowBg(true)
                .asBottomList(null, stringArr,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                Intent intent = new Intent(AnchorInfoActivity.this, ReportActivity.class);
                                intent.putExtra(Constant.KEY_REPORT_TYPE, text);
                                startActivity(intent);
                            }
                        })
                .show();

    }

    @Override
    public void liveApplySuccess() {

    }

    @Override
    public void sayHelloSuccess() {

    }

    @Override
    public void sayHelloFailed(String msg) {

    }


    public Chip generateHobby(String hobby) {
        Chip chip = new Chip(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, -2);
        layoutParams.setMargins(0, DisplayUtils.dip2px(this, 5), DisplayUtils.dip2px(this, 5), 0);
        chip.setLayoutParams(layoutParams);
        chip.setText(hobby);
        return chip;
    }

    public View generateGift(String path, String num) {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_gift_received, null);
        TextView tvGiftNum = view.findViewById(R.id.tvGiftNum);
        ImageView ivGift = view.findViewById(R.id.ivGift);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(-2, -2);
        int screenWidth = DisplayUtils.getScreenWidth(this);
        int i = DisplayUtils.dip2px(this, 55);
        int giftWidth = (screenWidth - i) / 4;
        layoutParams.width = giftWidth;
        view.setLayoutParams(layoutParams);
        ViewGroup.LayoutParams params = ivGift.getLayoutParams();
        params.width = giftWidth - DisplayUtils.dpTpx(this, 5);
        params.height = giftWidth - DisplayUtils.dpTpx(this, 5);
        ivGift.setLayoutParams(params);
        Glide.with(this)
                .load(path)
                .into(ivGift);
        tvGiftNum.setText("x " + num);
        return view;
    }

    public View generateVideoShow(String path, String videoPath) {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_video_show, null);
        TextView tvVideo = view.findViewById(R.id.ivVoicePlay);
        AppUtils.setFont(this, tvVideo);
        RoundedImageView ivVideoShow = view.findViewById(R.id.ivVideoCover);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(-2, -2);
        int screenWidth = DisplayUtils.getScreenWidth(this);
        int i = DisplayUtils.dip2px(this, 55);
        int giftWidth = (screenWidth - i) / 4;
        layoutParams.width = giftWidth;
        view.setLayoutParams(layoutParams);
        ViewGroup.LayoutParams params = ivVideoShow.getLayoutParams();
        params.width = giftWidth - DisplayUtils.dpTpx(this, 5);
        params.height = giftWidth * 3 / 2;
        ivVideoShow.setLayoutParams(params);
        Glide.with(this)
                .load(TextUtils.isEmpty(path) ? videoPath : path)
                .error(R.drawable.ic_placeholder)
                .into(ivVideoShow);
        RelativeLayout container = view.findViewById(R.id.rl_container);
        container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AnchorInfoActivity.this, VideoPlayActivity.class);
                intent.putExtra(Constant.KEY_VIDEO_URL, videoPath);
                startActivity(intent);
            }
        });
        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivVideoArrow:
                break;
            case R.id.ivGiftArrow:
                Intent intent = new Intent(this, GiftReceivedActivity.class);
                intent.putExtra(Constant.KEY_ANCHOR_ID, anchorID);
                startActivity(intent);
                break;
            case R.id.tv_function:
                new XPopup.Builder(this)
                        .atView(tvFunction)
                        .hasShadowBg(false)
                        .asCustom(new CustomBubbleAttachPopup(this, mHasBlacked, mHasFollowed, new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                handlePopupAction(position);
                            }
                        }))
                        .show();
                break;
            case R.id.tvAccost:
                break;
            case R.id.llVideoCall:
                break;
            case R.id.llMesssageChat:
                goMessageChat();
                break;
            case R.id.llGiftSend:
                break;
        }
    }

    private void goMessageChat() {
        Intent intent = new Intent(this, ChatActivity.class);
        intent.putExtra(Constant.C2C_CONVERSATION_ID, "c2c_"+anchorID);
        intent.putExtra(Constant.C2C_USER_ID, anchorID);
        intent.putExtra(Constant.C2C_SHOW_NAME, tvName.getText().toString());
        intent.putExtra(Constant.C2C_FACE_URL, mAvatarUrl);
        intent.putExtra(Constant.C2C_DRAFT_TEXT, "");
        startActivity(intent);
    }

    private void handlePopupAction(int position) {
        switch (position) {
            case 0:
                mPresenter.setFollowed(anchorID, mHasFollowed ? "0" : "1");
                break;
            case 1:
                if (mHasBlacked) {
                    mPresenter.blackRemove(anchorID);
                } else {
                    mPresenter.blackAdd(anchorID);
                }
                break;
            case 2:
                mPresenter.getReportType();
                break;
            case 3:
                showToast("分享");
                break;
        }
    }
}
